// 道具系统
class PowerUp {
    constructor(x, y, type) {
        this.x = x;
        this.y = y;
        this.type = type;
        this.radius = 12;
        this.lifetime = 30000; // 30秒后消失
        this.spawnTime = Date.now();
        this.bobOffset = 0;
        this.rotationAngle = 0;
        this.collected = false;
        
        // 道具属性
        this.powerUpData = this.getPowerUpData(type);
        
        // 发光效果
        this.glowRadius = 20;
        this.glowIntensity = 0.5;
    }
    
    getPowerUpData(type) {
        const powerUps = {
            'health': {
                name: '医疗包',
                color: '#00FF00',
                glowColor: '#00FF00',
                icon: '❤️',
                effect: 'heal',
                value: 50,
                description: '恢复50点血量'
            },
            'ammo': {
                name: '弹药箱',
                color: '#FFD700',
                glowColor: '#FFD700',
                icon: '📦',
                effect: 'ammo',
                value: 100,
                description: '补充弹药'
            },
            'speed': {
                name: '速度药剂',
                color: '#00FFFF',
                glowColor: '#00FFFF',
                icon: '⚡',
                effect: 'speed',
                value: 10000, // 持续时间(毫秒)
                description: '移动速度提升50%'
            },
            'damage': {
                name: '伤害强化',
                color: '#FF4500',
                glowColor: '#FF4500',
                icon: '💥',
                effect: 'damage',
                value: 15000,
                description: '伤害提升100%'
            },
            'shield': {
                name: '护盾',
                color: '#4169E1',
                glowColor: '#4169E1',
                icon: '🛡️',
                effect: 'shield',
                value: 3, // 可抵挡攻击次数
                description: '免疫3次攻击'
            },
            'rapid_fire': {
                name: '急速射击',
                color: '#FF69B4',
                glowColor: '#FF69B4',
                icon: '🔥',
                effect: 'rapid_fire',
                value: 12000,
                description: '射击速度提升200%'
            },
            'explosive': {
                name: '爆炸弹药',
                color: '#FF0000',
                glowColor: '#FF0000',
                icon: '💣',
                effect: 'explosive',
                value: 20, // 爆炸子弹数量
                description: '子弹带有爆炸效果'
            }
        };
        
        return powerUps[type] || powerUps['health'];
    }
    
    update(deltaTime) {
        // 上下浮动动画
        this.bobOffset = Math.sin(Date.now() * 0.005) * 3;
        
        // 旋转动画
        this.rotationAngle += deltaTime * 0.002;
        
        // 发光效果变化
        this.glowIntensity = 0.3 + Math.sin(Date.now() * 0.008) * 0.2;
        
        // 检查是否过期
        return Date.now() - this.spawnTime < this.lifetime;
    }
    
    collect(player) {
        if (this.collected) return false;
        
        const distance = Math.sqrt(
            Math.pow(this.x - player.x, 2) + Math.pow(this.y - player.y, 2)
        );
        
        if (distance < this.radius + player.radius) {
            this.collected = true;
            this.applyEffect(player);
            this.createCollectEffect();
            return true;
        }
        
        return false;
    }
    
    applyEffect(player) {
        const data = this.powerUpData;
        
        switch (data.effect) {
            case 'heal':
                player.heal(data.value);
                this.showFloatingText(`+${data.value} 血量`, '#00FF00');
                break;
                
            case 'ammo':
                if (player.currentWeapon) {
                    player.currentWeapon.totalAmmo += data.value;
                    player.updateWeaponUI();
                }
                this.showFloatingText(`+${data.value} 弹药`, '#FFD700');
                break;
                
            case 'speed':
                player.applySpeedBoost(1.5, data.value);
                this.showFloatingText('速度提升!', '#00FFFF');
                break;
                
            case 'damage':
                player.applyDamageBoost(2.0, data.value);
                this.showFloatingText('伤害提升!', '#FF4500');
                break;
                
            case 'shield':
                player.addShield(data.value);
                this.showFloatingText(`护盾 x${data.value}`, '#4169E1');
                break;
                
            case 'rapid_fire':
                player.applyRapidFire(3.0, data.value);
                this.showFloatingText('急速射击!', '#FF69B4');
                break;
                
            case 'explosive':
                player.addExplosiveAmmo(data.value);
                this.showFloatingText(`爆炸弹药 x${data.value}`, '#FF0000');
                break;
        }
        
        // 记录道具收集统计
        if (window.storageManager) {
            window.storageManager.updateStatistics('powerUpCollected');
        }
        
        console.log(`拾取道具: ${data.name}`);
    }
    
    createCollectEffect() {
        if (window.gameEngine) {
            for (let i = 0; i < 12; i++) {
                const angle = (Math.PI * 2 / 12) * i;
                window.gameEngine.particles.push(new Particle(
                    this.x,
                    this.y,
                    Math.cos(angle) * 80,
                    Math.sin(angle) * 80,
                    this.powerUpData.color,
                    1000
                ));
            }
        }
    }
    
    showFloatingText(text, color) {
        if (window.gameEngine) {
            window.gameEngine.floatingTexts = window.gameEngine.floatingTexts || [];
            window.gameEngine.floatingTexts.push(new FloatingText(
                this.x, this.y - 20, text, color, 2000
            ));
        }
    }
    
    render(ctx) {
        if (this.collected) return;
        
        ctx.save();
        ctx.translate(this.x, this.y + this.bobOffset);
        ctx.rotate(this.rotationAngle);
        
        // 绘制发光效果
        ctx.globalAlpha = this.glowIntensity;
        ctx.fillStyle = this.powerUpData.glowColor;
        ctx.beginPath();
        ctx.arc(0, 0, this.glowRadius, 0, Math.PI * 2);
        ctx.fill();
        
        ctx.globalAlpha = 1;
        
        // 绘制道具主体
        ctx.fillStyle = this.powerUpData.color;
        ctx.beginPath();
        ctx.arc(0, 0, this.radius, 0, Math.PI * 2);
        ctx.fill();
        
        // 绘制道具图标
        ctx.fillStyle = '#FFFFFF';
        ctx.font = '16px monospace';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(this.powerUpData.icon, 0, 0);
        
        // 绘制道具名称（当靠近时显示）
        if (window.player) {
            const distance = Math.sqrt(
                Math.pow(this.x - window.player.x, 2) + Math.pow(this.y - window.player.y, 2)
            );
            
            if (distance < 60) {
                ctx.fillStyle = 'rgba(0, 0, 0, 0.8)';
                ctx.fillRect(-40, -35, 80, 20);
                
                ctx.fillStyle = '#FFFFFF';
                ctx.font = '10px monospace';
                ctx.fillText(this.powerUpData.name, 0, -25);
            }
        }
        
        ctx.restore();
    }
}

// 浮动文字类
class FloatingText {
    constructor(x, y, text, color, duration) {
        this.x = x;
        this.y = y;
        this.text = text;
        this.color = color;
        this.duration = duration;
        this.startTime = Date.now();
        this.startY = y;
    }
    
    update(deltaTime) {
        const elapsed = Date.now() - this.startTime;
        const progress = elapsed / this.duration;
        
        // 向上飘动
        this.y = this.startY - progress * 50;
        
        return elapsed < this.duration;
    }
    
    render(ctx) {
        const elapsed = Date.now() - this.startTime;
        const progress = elapsed / this.duration;
        const alpha = 1 - progress;
        
        ctx.save();
        ctx.globalAlpha = alpha;
        ctx.fillStyle = this.color;
        ctx.font = 'bold 14px monospace';
        ctx.textAlign = 'center';
        ctx.strokeStyle = '#000000';
        ctx.lineWidth = 2;
        ctx.strokeText(this.text, this.x, this.y);
        ctx.fillText(this.text, this.x, this.y);
        ctx.restore();
    }
}

// 道具生成器
class PowerUpSpawner {
    constructor() {
        this.spawnTimer = 0;
        this.spawnInterval = 15000; // 15秒生成一个道具
        this.maxPowerUps = 3; // 同时最多3个道具
        this.powerUpTypes = ['health', 'ammo', 'speed', 'damage', 'shield', 'rapid_fire', 'explosive'];
    }
    
    update(deltaTime) {
        this.spawnTimer += deltaTime;
        
        if (this.spawnTimer >= this.spawnInterval) {
            this.trySpawnPowerUp();
            this.spawnTimer = 0;
        }
    }
    
    trySpawnPowerUp() {
        if (!window.gameEngine || !window.gameEngine.powerUps) {
            return;
        }
        
        // 检查当前道具数量
        const currentPowerUps = window.gameEngine.powerUps.filter(p => !p.collected);
        if (currentPowerUps.length >= this.maxPowerUps) {
            return;
        }
        
        // 随机选择道具类型
        const randomType = this.powerUpTypes[Math.floor(Math.random() * this.powerUpTypes.length)];
        
        // 随机生成位置（避免在边缘）
        const canvas = document.getElementById('gameCanvas');
        const margin = 100;
        const x = Math.random() * (canvas.width - 2 * margin) + margin;
        const y = Math.random() * (canvas.height - 2 * margin) + margin;
        
        const powerUp = new PowerUp(x, y, randomType);
        window.gameEngine.powerUps.push(powerUp);
        
        console.log(`生成道具: ${powerUp.powerUpData.name} 在位置 (${x}, ${y})`);
    }
    
    spawnSpecificPowerUp(type, x, y) {
        if (!window.gameEngine) return;
        
        window.gameEngine.powerUps = window.gameEngine.powerUps || [];
        const powerUp = new PowerUp(x, y, type);
        window.gameEngine.powerUps.push(powerUp);
        
        return powerUp;
    }
}